import 'dart:convert';
import 'dart:io';
import 'dart:isolate';
import 'dart:math';
import 'dart:typed_data';
import 'dart:ui';

import 'package:file_picker/file_picker.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_cache_manager/flutter_cache_manager.dart';
import 'package:flutter_downloader/flutter_downloader.dart';
import 'package:flutter_image_compress/flutter_image_compress.dart';
import 'package:path_provider/path_provider.dart';
import 'package:permission_handler/permission_handler.dart';
import 'downloadHelper.dart';
import 'fileHelper.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:url_launcher/url_launcher.dart';
import '../helper/cacheHelper.dart';
import 'dioHelper2.dart';
import 'downloadCBH.dart';
import 'uidata.dart';
//import 'package:flutter_image_compress/flutter_image_compress.dart';
import 'package:uuid/uuid.dart';

import 'upload_helper.dart';

//import 'cacheHelper.dart';
typedef RefrushCallback = void Function();
typedef onChanged = void Function(dynamic);
typedef onStrChanged = void Function(String img1);
typedef ProgressCallback = void Function(String id, int value);

class Helper {
//获取Img 网址
  static ReceivePort _port = ReceivePort();
  static void Init() {
    GetDirPath();
    CacheHelper.Init();
    getLocalDB();
    // FlutterDownloader.registerCallback(downloadCallback);
    registDownLoad();
    registUpload();
    //891  CacheHelper.Init();
  }

  static SharedPreferences localDB = null as SharedPreferences;
  static final fileCache = DefaultCacheManager();

  static Future getLocalDB() async {
    localDB = await SharedPreferences.getInstance();
  }

  static Color getRandomColor(
      {int r = 255, int g = 255, int b = 255, a = 255}) {
    if (r == 0 || g == 0 || b == 0) return Colors.black;
    if (a == 0) return Colors.white;
    return Color.fromARGB(
      a,
      r != 255 ? r : Random.secure().nextInt(r),
      g != 255 ? g : Random.secure().nextInt(g),
      b != 255 ? b : Random.secure().nextInt(b),
    );
  }

  static registUpload() {
    if (UploadHelper.IfInit2 == true) return;
    UploadHelper.IfInit2 = true;
    UploadHelper.uploader.progress.listen((progress) {
      FileLoadProgress()
          .fire(progress.taskId, DownloadTaskStatus.running, progress.progress);
    });
  }

  static void registDownLoad() {
    IsolateNameServer.registerPortWithName(
        _port.sendPort, 'downloader_send_port');
    _port.listen((dynamic data) {
      String id = data[0];
      DownloadTaskStatus status = data[1];
      int progress = data[2];
      FileLoadProgress().fire(id, status, progress);
    });

    FlutterDownloader.registerCallback(downloadCallback);
  }

  static void downloadCallback(
      String id, DownloadTaskStatus status, int progress) {
    // print([id, status, progress]);
    final SendPort send =
        IsolateNameServer.lookupPortByName('downloader_send_port')!;
    send.send([id, status, progress]);

    //eventBus.fire(FileLoadProgressInEvent(id,progress));
  }

  static String StrNull(String p) {
    if (p == null) return '';
    return p;
  }

  static bool isChinaPhoneLegal(String str) {
    return new RegExp(
            '^((13[0-9])|(15[^4])|(166)|(17[0-8])|(18[0-9])|(19[8-9])|(147,145))\\d{8}\$')
        .hasMatch(str);
  }

  static Future<File> ImgRotate(File file) async {
    String rand = uuid.v4();
    rand = rand.replaceAll("-", "_");
    //var rand=Math.Random().nextInt(10000).toString();
    String targetPath = DirPath.path + "/img_" + rand + ".jpg";

    var result = await FlutterImageCompress.compressAndGetFile(
      file.absolute.path,
      targetPath,
      quality: 100,
      rotate: 90,
      keepExif: true,
    );
    //print(file.lengthSync());
    // print(result.lengthSync());
    file.deleteSync();
    return result!;
  }

  static Future<File> ImgCompress(File file) async {
    String rand = uuid.v4();
    rand = rand.replaceAll("-", "_");
    //var rand=Math.Random().nextInt(10000).toString();
    String targetPath = DirPath.path + "/img_" + rand + ".jpg";

    var result = await FlutterImageCompress.compressAndGetFile(
      file.absolute.path,
      targetPath,
      quality: 90,
      keepExif: true,
    );
    //print(file.lengthSync());
    // print(result.lengthSync());
    return result!;
  }

  static Future<String> GetImageBase64(String imgId) async {
    var url = GetImgUrlOld(imgId);
    //var path=GetRandPath3(imgId, ".png");
    var path = await FileHelper.DownLoad(url, imgId);
    var base = await ImageToBase64(File(path));
    return base;
  }

  static Future<String> ImageToBase64(File value) async {
    List<int> bytes = await value.readAsBytes();

    String bs64 = base64Encode(bytes);

    String bs64Image = "data:image/png;base64," + bs64;
    return bs64Image;
//print(bs64Image);
  }

  static Future<String> ImageToBase642(List<int> bytes) async {
    String bs64 = base64Encode(bytes);

    String bs64Image = "data:image/png;base64," + bs64;
    return bs64Image;
//print(bs64Image);
  }

  static Widget Base64ToImage(String CaptchaCode) {
    if (!CaptchaCode.contains("data:image/png;base64,")) return Container();

    CaptchaCode = CaptchaCode.replaceAll("data:image/png;base64,", "");
    Uint8List bytes = Base64Decoder().convert(CaptchaCode);

    if (bytes != null) {
      return Image.memory(
        bytes,
        fit: BoxFit.contain,
      );
    } else {
      return Container();
    }
  }

  static MemoryImage Base64ToImage2(String CaptchaCode) {
    CaptchaCode = CaptchaCode.replaceAll("data:image/png;base64,", "");
    Uint8List bytes = const Base64Decoder().convert(CaptchaCode);
    return MemoryImage(bytes);
  }

  static CallPhone(String p) async {
    var url = Uri.parse("tel:$p");
    await launchUrl(url);
  }

  static String GetImgUrl(String ImgId) {
    return UIData.imageDownloadServer + ImgId;
  }

  static String GetImgUrl2(String ImgId) {
    return UIData.imageDownloadServer2 + ImgId;
  }

  static String GetImgUrlOld(String ImgId) {
    return UIData.fileDownloadServerOld + ImgId;
  }

  static String GetUrl(String Id) {
    return UIData.fileDownloadServer + Id;
  }

//时间格式化
  static String DateTimeNowString() {
    var date = DateTime.now();
    String timestamp =
        "${date.year.toString()}-${date.month.toString().padLeft(2, '0')}-${date.day.toString().padLeft(2, '0')} ${date.hour.toString().padLeft(2, '0')}:${date.minute.toString().padLeft(2, '0')}";
    return timestamp;
  }

  static String DateTimeTodayString() {
    var date = DateTime.now();
    String timestamp =
        "${date.year.toString()}-${date.month.toString().padLeft(2, '0')}-${date.day.toString().padLeft(2, '0')}";
    return timestamp;
  }

  static String DateTimeYestodayString() {
    var date = DateTime.now();
    date = date.add(const Duration(days: -1));
    String timestamp =
        "${date.year.toString()}-${date.month.toString().padLeft(2, '0')}-${date.day.toString().padLeft(2, '0')}";
    return timestamp;
  }

  static String DateTimeMonthString() {
    var date = DateTime.now();
    String timestamp =
        "${date.year.toString()}-${date.month.toString().padLeft(2, '0')}-01";
    return timestamp;
  }

  static String DateTimeYearString() {
    var date = DateTime.now();
    String timestamp = "${date.year.toString()}-01-01";
    return timestamp;
  }

  static Future<String?> getFilePickPath() async {
    var result = await FilePicker.platform.pickFiles();

    return result?.files.first.path;
  }

  static Future<bool> GetstoragePermission() async {
    await [
      Permission.storage,
    ].request();

    Map<Permission, PermissionStatus> statuses =
        await [Permission.storage].request();
    print(statuses[Permission.storage]);
    var status = await Permission.storage.status;
    if (status.isGranted) {
      return true;
    } else {
      return false;
    }
  }

//检查定位权限
  static Future<bool> CheckLocationPersmission() async {
    Map<Permission, PermissionStatus> statuses =
        await [Permission.location].request();

    var status = await Permission.location.status;
    if (status.isGranted) {
      return true;
    } else {
      return false;
    }
  }

  static Future<bool> CheckLocationPersmission2() async {
    Map<Permission, PermissionStatus> statuses =
        await [Permission.locationAlways].request();

    var status = await Permission.locationWhenInUse.status;
    if (status.isGranted) {
      return true;
    } else {
      return false;
    }
  }

  static int DateTimeByNow(String date1) {
    var t1 = DateTime.parse(date1);
    if (t1 == null) return 0;

    var t2 = DateTime.now();
    return t2.difference(t1).inMinutes;
  }

  static String DateTimeToString(DateTime date) {
    if (date == null) return "";
    String timestamp =
        "${date.year.toString()}-${date.month.toString().padLeft(2, '0')}-${date.day.toString().padLeft(2, '0')} ${date.hour.toString().padLeft(2, '0')}:${date.minute.toString().padLeft(2, '0')}";
    return timestamp;
  }

  static String DateTimeFormat(String date1) {
    var date = DateTime.tryParse(date1);
    if (date == null) return "";
    String timestamp =
        "${date.year.toString()}-${date.month.toString().padLeft(2, '0')}-${date.day.toString().padLeft(2, '0')} ${date.hour.toString().padLeft(2, '0')}:${date.minute.toString().padLeft(2, '0')}";
    return timestamp;
  }

  static String DateTimeFormat2(String date1) {
    var date = DateTime.parse(date1);
    if (date == null) return "";
    String timestamp =
        "${date.year.toString()}-${date.month.toString().padLeft(2, '0')}-${date.day.toString().padLeft(2, '0')}";
    return timestamp;
  }

  static String DateTimeFormat3(String date1) {
    var date = DateTime.parse(date1);
    if (date == null) return "";
    String timestamp =
        "${date.year.toString()}年${date.month.toString().padLeft(2, '0')}月${date.day.toString().padLeft(2, '0')}日";
    return timestamp;
  }

  static String DateTimeFormat4(String date1) {
    var date = DateTime.parse(date1);
    if (date == null) return "";
    String timestamp = "${date.day.toString()}日${date.hour.toString()}时";
    return timestamp;
  }

  static String DateTimeFormat5(String date1) {
    var date = DateTime.parse(date1);
    if (date == null) return "";
    String timestamp = "${date.day.toString()}日";
    return timestamp;
  }

  static String DateTimeFormat6(String date1) {
    var date = DateTime.tryParse(date1);
    if (date == null) return "";
    String timestamp =
        "${date.month.toString().padLeft(2, '0')}/${date.day.toString().padLeft(2, '0')} ${date.hour.toString().padLeft(2, '0')}:${date.minute.toString().padLeft(2, '0')}";
    return timestamp;
  }

  static Directory DirPath = Directory("");

  static void GetDirPath() async {
    //DirPath = await getApplicationDocumentsDirectory();
    DirPath = (await getExternalStorageDirectory()!)!;
  }

  static final uuid = new Uuid();

  static String GetGuid() {
    return uuid.v4();
  }

  static bool StrPB(String s1, s2) {
    if (s1.toLowerCase() == s2.toLowerCase()) return true;
    return false;
  }

  static bool UserPB(String s1) {
    return StrPB(s1, UIData.CurrentUser!.Guid);
  }

  static bool AuthPB(String s1) {
    return UIData.CurrentUser!.Authority.contains(s1);
  }

  //获取随机文件路径
  static String GetRandPath() {
    var rand = GetGuid();
    return DirPath.path + '/' + rand;
  }

  static String GetRandPath2(String basename) {
    var rand = GetGuid();
    return DirPath.path + '/' + rand + "_" + basename;
  }

  static String GetRandPath3(String baseName, String hzName) {
    var rand = GetGuid();
    return DirPath.path + '/' + baseName + "_" + rand + hzName;
  }

  static int GetInt(String st) {
    if (st == null) return 0;
    if (st == "") return 0;
    return int.parse(st);
  }

  static double GetDouble(String st) {
    if (st == 'NA') return 0;
    if (st == null) return 0;
    if (st == "") return 0;
    return double.parse(st);
  }

  static double RoundUp10(double toRound, double x) {
    if (toRound == null) return 0;
    return (x - toRound % x) + toRound;
  }

  static double RoundDown10(double toRound, double x) {
    if (toRound == null) return 0;
    return toRound - toRound % x;
  }

  static String RoundDouble(double toRound, int h, String hzm) {
    if (toRound == null) return "";
    return toRound.toStringAsFixed(h) + hzm;
  }

  static String RoundDouble2(double toRound, int h) {
    if (toRound == null) return "";
    return toRound.toStringAsFixed(h);
  }

  static String GetFileSize(int size) {
    var num = 1024.00; //byte

    if (size < num) return size.toString() + "B";
    if (size < pow(num, 2)) return (size / num).toStringAsFixed(2) + "K"; //kb
    if (size < pow(num, 3))
      return (size / pow(num, 2)).toStringAsFixed(2) + "M"; //M
    if (size < pow(num, 4))
      return (size / pow(num, 3)).toStringAsFixed(2) + "G"; //G

    return (size / pow(num, 4)).toStringAsFixed(2) + "T"; //T
  }

  //SendMessage 发送短信
  static Future<bool> sendMessage(String title, String phone) async {
    //return null;

    var response =
        await DioHelper.Get("/User/SendMessage?title=$title&phone=$phone", {
      "Where": "",
    });

    if (response.statusCode == 200) return true;
    return false;
  }

  static int toInt(num val) {
    if (val == null) {
      return 0;
    }
    if (val is int) {
      return val;
    } else {
      return val.toInt();
    }
  }

  static String toStr(String? val) {
    if (val == null) {
      return "";
    }
    return val;
  }

  /*static final AudioPlayer audioPlayr = new AudioPlayer();

  ///播放音频
  static void AudioPlay(String path) {
    if (audioPlayr.state == AudioPlayerState.PLAYING) {
      audioPlayr.stop();
      audioPlayr.play(path);
    } else {
      audioPlayr.play(path);
    }
  }

  static void AudioPlayUrl(String url) {
    if (audioPlayr.state == AudioPlayerState.PLAYING) {
      audioPlayr.stop();
      audioPlayr.play(url,isLocal: false);
    } else {
      audioPlayr.play(url,isLocal: false);
    }
  }
*/
}
